<template>
  <layout-content
    v-loading="uiState.loading"
    :header="$t('commons.form.detail')"
    :back-to="{ name: 'Nodes' }"
  >
    <div v-if="!query.yaml && detailsModel">
      <el-row :gutter="20">
        <el-col :span="15">
          <el-card class="el-card">
            <ko-detail-basic
              v-model:yaml-show="query.yaml"
              :item="detailsModel"
            />
          </el-card>
        </el-col>
        <el-col :span="9">
          <el-card class="el-card">
            <table style="width: 100%" class="myTable">
              <tr>
                <th scope="col" width="30%" align="left">
                  <h3>{{ $t("business.common.system") }}</h3>
                </th>
                <th scope="col" />
              </tr>
              <tr>
                <td>
                  <el-text>{{ $t("business.node.arch") }}</el-text>
                </td>
                <td>{{ detailsModel.status.nodeInfo.architecture }}</td>
              </tr>
              <tr>
                <td>
                  <el-text>{{ $t("business.node.os") }}</el-text>
                </td>
                <td>{{ detailsModel.status.nodeInfo.operatingSystem }}</td>
              </tr>
              <tr>
                <td>
                  <el-text>{{ $t("business.node.osImage") }}</el-text>
                </td>
                <td>{{ detailsModel.status.nodeInfo.osImage }}</td>
              </tr>
              <tr>
                <td>
                  <el-text>{{ $t("business.node.kernel") }}</el-text>
                </td>
                <td>{{ detailsModel.status.nodeInfo.kernelVersion }}</td>
              </tr>
              <tr>
                <td>
                  <el-text>{{ $t("business.node.container") }}</el-text>
                </td>
                <td>
                  {{ detailsModel.status.nodeInfo.containerRuntimeVersion }}
                </td>
              </tr>
              <tr>
                <td>
                  <el-text>{{ $t("business.node.kubelet_version") }}</el-text>
                </td>
                <td>{{ detailsModel.status.nodeInfo.kubeletVersion }}</td>
              </tr>
            </table>
          </el-card>
        </el-col>
      </el-row>
      <br />
      <div
        v-has-permissions="{
          scope: 'namespace',
          apiGroup: '',
          resource: 'pods',
          verb: 'list'
        }"
        class="row-box w-full"
      >
        <el-card class="el-card">
          <h4>{{ $t("business.node.allocata") }}</h4>
          <el-form label-position="top">
            <el-row class="w-full">
              <el-col :span="4">
                <el-form-item
                  :label="'CPU ' + $t('business.workload.reservation')"
                >
                  <span>
                    {{ nodeUsage.cpuUsage.toFixed(2) }} core ({{
                      nodeUsage.cpuUsagePercent
                    }}%)
                  </span>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item :label="'CPU ' + $t('business.workload.limit')">
                  <span>
                    {{ nodeUsage.cpuLimit.toFixed(2) }} core ({{
                      nodeUsage.cpuLimitPercent
                    }}%)
                  </span>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item
                  :label="
                    $t('business.workload.memory') +
                    $t('business.workload.reservation')
                  "
                >
                  <span>
                    {{ nodeUsage.memoryUsage.toFixed(2) }} Gi ({{
                      nodeUsage.memoryUsagePercent
                    }}%)
                  </span>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item
                  :label="
                    $t('business.workload.memory') +
                    $t('business.workload.limit')
                  "
                >
                  <span>
                    {{ nodeUsage.memoryLimit.toFixed(2) }} Gi ({{
                      nodeUsage.memoryLimitPercent
                    }}%)
                  </span>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="Pods">
                  <span>
                    {{ nodePods.length }}/{{
                      detailsModel?.status?.allocatable?.pods ?? 0
                    }}
                    ({{
                      (nodePods.length /
                        (detailsModel?.status?.allocatable?.pods ?? 0)) *
                      100
                    }}%)
                  </span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
      <br />
      <div
        v-has-permissions="{
          scope: 'namespace',
          apiGroup: '',
          resource: 'pods',
          verb: 'list'
        }"
        class="row-box"
      >
        <el-card class="el-card">
          <div class="flex flex-col w-full">
            <h4>{{ $t("business.node.health_statu") }}</h4>
            <el-form label-position="top">
              <div class="w-full flex">
                <div
                  v-for="(cond, index) in detailsModel.status.conditions"
                  :key="index"
                  class="w-1/4"
                >
                  <div v-if="cond.type === 'NetworkUnavailable'" class="w-full">
                    <div class="ml-2">
                      <el-icon><Memo /></el-icon>
                      <el-icon>
                        <SuccessFilled
                          v-if="cond.status === 'False'"
                          color="var(--el-color-success)"
                        />
                        <WarningFilled
                          v-else-if="cond.status === 'True'"
                          color="var(--el-color-warning)"
                        />
                      </el-icon>
                    </div>
                    <el-tooltip class="item" effect="dark" placement="top">
                      <template v-slot:content>
                        <div>
                          <div>
                            <span style="font-wight: blod">
                              {{ cond.reason }}
                            </span>
                          </div>
                          <div style="margin-top: 5px">
                            <span>{{ cond.message }}</span>
                          </div>
                          <div style="margin-top: 2px">
                            <span
                              >{{ $t("business.pod.lastUpdateTime") }}:
                              {{ getAge(cond.lastTransitionTime) }}</span
                            >
                          </div>
                        </div>
                      </template>
                      <el-form-item
                        style="float: left; margin-left: 8px"
                        :label="$t('business.node.network_statu')"
                      >
                        <span>
                          {{ $t("business.node.network_statu_help") }}
                        </span>
                      </el-form-item>
                    </el-tooltip>
                  </div>
                  <div
                    v-else-if="cond.type === 'MemoryPressure'"
                    class="w-full"
                  >
                    <div class="ml-2">
                      <el-icon><Memo /></el-icon>
                      <el-icon>
                        <SuccessFilled
                          v-if="cond.status === 'False'"
                          color="var(--el-color-success)"
                        />
                        <WarningFilled
                          v-else-if="cond.status === 'True'"
                          color="var(--el-color-warning)"
                        />
                      </el-icon>
                    </div>
                    <el-tooltip class="item" effect="dark" placement="top">
                      <template #content>
                        <div>
                          <div>
                            <span style="font-wight: blod">
                              {{ cond.reason }}
                            </span>
                          </div>
                          <div style="margin-top: 5px">
                            <span>{{ cond.message }}</span>
                          </div>
                          <div style="margin-top: 2px">
                            <span>
                              {{ $t("business.pod.lastUpdateTime") }}:
                              {{ getAge(cond.lastTransitionTime) }}
                            </span>
                          </div>
                        </div>
                      </template>
                      <el-form-item
                        style="float: left; margin-left: 8px"
                        :label="$t('business.node.memory_statu')"
                      >
                        <span>{{ $t("business.node.memory_statu_help") }}</span>
                      </el-form-item>
                    </el-tooltip>
                  </div>
                  <div v-else-if="cond.type === 'DiskPressure'" class="w-full">
                    <div class="ml-2">
                      <el-icon><Memo /></el-icon>
                      <el-icon>
                        <SuccessFilled
                          v-if="cond.status === 'False'"
                          color="var(--el-color-success)"
                        />
                        <WarningFilled
                          v-else-if="cond.status === 'True'"
                          color="var(--el-color-warning)"
                        />
                      </el-icon>
                    </div>
                    <el-tooltip class="item" effect="dark" placement="top">
                      <template v-slot:content>
                        <div>
                          <div>
                            <span style="font-wight: blod">
                              {{ cond.reason }}
                            </span>
                          </div>
                          <div style="margin-top: 5px">
                            <span>{{ cond.message }}</span>
                          </div>
                          <div style="margin-top: 2px">
                            <span
                              >{{ $t("business.pod.lastUpdateTime") }}:
                              {{ getAge(cond.lastTransitionTime) }}</span
                            >
                          </div>
                        </div>
                      </template>
                      <el-form-item
                        style="float: left; margin-left: 8px"
                        :label="$t('business.node.disk_statu')"
                      >
                        <span>{{ $t("business.node.disk_statu_help") }}</span>
                      </el-form-item>
                    </el-tooltip>
                  </div>
                  <div v-else-if="cond.type === 'PIDPressure'" class="w-full">
                    <div class="ml-2">
                      <el-icon><Memo /></el-icon>
                      <el-icon>
                        <SuccessFilled
                          v-if="cond.status === 'False'"
                          color="var(--el-color-success)"
                        />
                        <WarningFilled
                          v-else-if="cond.status === 'True'"
                          color="var(--el-color-warning)"
                        />
                      </el-icon>
                    </div>
                    <el-tooltip class="item" effect="dark" placement="top">
                      <template v-slot:content>
                        <div>
                          <div>
                            <span style="font-wight: blod">{{
                              cond.reason
                            }}</span>
                          </div>
                          <div style="margin-top: 5px">
                            <span>{{ cond.message }}</span>
                          </div>
                          <div style="margin-top: 2px">
                            <span
                              >{{ $t("business.pod.lastUpdateTime") }}:
                              {{ getAge(cond.lastTransitionTime) }}</span
                            >
                          </div>
                        </div>
                      </template>
                      <el-form-item
                        style="float: left; margin-left: 8px"
                        :label="$t('business.node.pid_statu')"
                      >
                        <span>{{ $t("business.node.pid_statu_help") }}</span>
                      </el-form-item>
                    </el-tooltip>
                  </div>
                  <div v-else-if="cond.type === 'Ready'" class="w-full">
                    <div>
                      <el-icon><Memo /></el-icon>
                      <el-icon>
                        <SuccessFilled
                          v-if="cond.status === 'False'"
                          color="var(--el-color-success)"
                        />
                        <WarningFilled
                          v-else-if="cond.status === 'True'"
                          color="var(--el-color-warning)"
                        />
                      </el-icon>
                    </div>
                    <el-tooltip class="w-full" effect="dark" placement="top">
                      <template #content>
                        <div class="w-full">
                          <div>
                            <span style="font-wight: blod">
                              {{ cond.reason }}
                            </span>
                          </div>
                          <div style="margin-top: 5px">
                            <span>{{ cond.message }}</span>
                          </div>
                          <div style="margin-top: 2px">
                            <span>
                              {{ $t("business.pod.lastUpdateTime") }}:
                              {{ getAge(cond.lastTransitionTime) }}
                            </span>
                          </div>
                        </div>
                      </template>
                      <el-form-item
                        class="w-full"
                        :label="$t('business.node.node_statu')"
                      >
                        <span>{{ $t("business.node.node_statu_help") }}</span>
                      </el-form-item>
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </el-form>
          </div>
        </el-card>
      </div>
      <div>
        <br />
        <el-tabs
          v-if="Object.keys(detailsModel.metadata).length > 0"
          type="border-card"
        >
          <el-tab-pane
            v-has-permissions="{
              scope: 'namespace',
              apiGroup: '',
              resource: 'pods',
              verb: 'list'
            }"
            label="Pods"
          >
            <ko-detail-node-pods
              :cluster="query.cluster"
              :allocatable="detailsModel.status.allocatable"
              :field-selector="'spec.nodeName=' + detailsModel.metadata.name"
              :pods="nodePods ?? []"
            />
          </el-tab-pane>
          <el-tab-pane :label="$t('business.pod.image')">
            <table style="width: 90%" class="myTable">
              <tr>
                <th scope="col" align="left">
                  {{ $t("commons.table.name") }}
                </th>
                <th scope="col" width="150px" align="left">
                  {{ $t("business.pod.size") }}
                </th>
              </tr>
              <tr
                v-for="(image, index) in detailsModel.status.images"
                v-bind:key="index"
              >
                <td>
                  <el-text>
                    {{ image.names[1] ? image.names[1] : image.names[0] }}
                  </el-text>
                </td>
                <td>
                  <el-text>
                    {{ Math.round(image.sizeBytes / (1024 * 1024)) }}
                    MB</el-text
                  >
                </td>
              </tr>
            </table>
          </el-tab-pane>
          <el-tab-pane :label="$t('business.pod.resource')">
            <table style="width: 100%" class="myTable">
              <tr>
                <td><el-text>Pod CIDR</el-text></td>
                <td>
                  <el-text tag="b"> {{ detailsModel.spec.podCIDR }}</el-text>
                </td>
              </tr>
              <tr>
                <td class="h-full flex items-start">
                  <el-text> {{ $t("business.pod.address") }}</el-text>
                </td>
                <td>
                  <div
                    v-for="(address, index) in detailsModel.status.addresses"
                    v-bind:key="index"
                  >
                    <el-tag type="success">
                      {{ address.type }} : {{ address.address }}
                    </el-tag>
                  </div>
                </td>
              </tr>
              <tr>
                <td class="h-full flex items-start">
                  <el-text> Allocatable</el-text>
                </td>
                <td>
                  <div>
                    <el-tag type="success">
                      CPU : {{ detailsModel.status.allocatable.cpu }}
                    </el-tag>
                  </div>
                  <div>
                    <el-tag type="success">
                      Memory : {{ detailsModel.status.allocatable.memory }}
                    </el-tag>
                  </div>
                  <div>
                    <el-tag type="success">
                      Pods : {{ detailsModel.status.allocatable.pods }}
                    </el-tag>
                  </div>
                </td>
              </tr>
              <tr>
                <td class="h-full flex items-start">
                  <el-text> Capacity</el-text>
                </td>
                <td>
                  <div>
                    <el-tag type="success">
                      CPU : {{ detailsModel.status.capacity.cpu }}
                    </el-tag>
                  </div>
                  <div>
                    <el-tag type="success">
                      Memory :
                      {{ detailsModel.status.capacity.memory }}
                    </el-tag>
                  </div>
                  <div>
                    <el-tag type="success">
                      Pods : {{ detailsModel.status.capacity.pods }}
                    </el-tag>
                  </div>
                </td>
              </tr>
            </table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div v-if="query.yaml">
      <yaml-editor :value="yamlDetailsModel" :read-only="true" />
      <div class="bottom-button">
        <el-button @click="query.yaml = !query.yaml">{{
          $t("commons.button.back_detail")
        }}</el-button>
      </div>
    </div>
  </layout-content>
</template>

<script setup lang="ts">
import LayoutContent from "@/views/domain/kubeHud/views/components/layout/LayoutContent.vue";
import YamlEditor from "@/views/domain/kubeHud/views/components/yaml-editor/index.vue";
import KoDetailNodePods from "@/views/domain/kubeHud/views/components/detail/detail-node-pods.vue";
import KoDetailBasic from "@/views/domain/kubeHud/views/components/detail/detail-basic.vue";
import { Pod, useK8SApi } from "@/views/domain/kubeHud/api/k8s";
import { useBaseDetailsProvider } from "@/views/domain/kubeHud/api/provider/baseDetailsProvider";
import { onMounted, ref } from "vue";
import {
  cpuUnitConvert,
  getCpuCores,
  miMemoryFormat
} from "@/views/domain/kubeHud/utils/unitConvert";
import { getAge } from "@/views/domain/kubeHud/utils";

const { nodeRepo, podRepo } = useK8SApi();

type PodUsage = {
  cpuLimit?: number; // 设定的阈值
  cpuUsage?: number; //使用数量
  cpuMax?: number; // 总量
  cpuLimitPercent?: number; // 设定阈值使用率
  cpuUsagePercent?: number; // 使用率
  memoryLimit?: number;
  memoryUsage?: number;
  memoryMax?: number;
  memoryLimitPercent?: number;
  memoryUsagePercent?: number;
};
const nodePods = ref<(Pod & PodUsage)[]>([]);
const nodeUsage = ref<PodUsage>({
  cpuMax: 0,
  memoryMax: 0,
  cpuLimit: 0,
  cpuUsage: 0,
  memoryLimit: 0,
  memoryUsage: 0
});

const {
  detailsModel,
  uiState,
  query,
  router,
  reloadDetails,
  reloadQuery,
  yamlDetailsModel
} = useBaseDetailsProvider({
  getDetailsReq: nodeRepo.getNodeDetail
});

const reloadDetailsData = async () => {
  await reloadQuery();
  // await reloadDetails();

  const { items } = await podRepo.getPodList({
    query: {
      fieldSelector: `spec.nodeName=${query.name}`
    }
  });
  if (items) {
    nodePods.value = items;
    updateUsage();
  }
};

const updateUsage = () => {
  nodeUsage.value = {
    cpuMax: parseFloat(detailsModel.value?.status?.allocatable?.cpu),
    memoryMax:
      miMemoryFormat(detailsModel.value?.status?.allocatable?.memory) / 1024,
    cpuLimit: 0,
    cpuUsage: 0,
    memoryLimit: 0,
    memoryUsage: 0
  };
  nodePods.value.forEach(pod => {
    pod.spec?.containers?.forEach(container => {
      nodeUsage.value.cpuLimit += getCpuCores(container.resources?.limits?.cpu);
      nodeUsage.value.memoryUsage +=
        miMemoryFormat(container.resources?.limits?.memory) / 1024;

      nodeUsage.value.cpuUsage += getCpuCores(
        container.resources?.requests?.cpu
      );
      nodeUsage.value.memoryLimit +=
        miMemoryFormat(container.resources?.requests?.memory) / 1024;
    });
  });

  nodeUsage.value.cpuLimitPercent = Math.floor(
    (nodeUsage.value.cpuLimit / nodeUsage.value.cpuMax) * 100
  );
  nodeUsage.value.memoryLimitPercent = Math.floor(
    (nodeUsage.value.memoryLimit / nodeUsage.value.memoryMax) * 100
  );
  nodeUsage.value.cpuUsagePercent = Math.floor(
    (nodeUsage.value.cpuUsage / nodeUsage.value.cpuMax) * 100
  );
  nodeUsage.value.memoryUsagePercent = Math.floor(
    (nodeUsage.value.memoryUsage / nodeUsage.value.memoryMax) * 100
  );
};

onMounted(() => {
  try {
    reloadDetailsData();
  } catch (e) {
    console.error(e);
    uiState.loading = false;
  }
});
</script>

<style scoped lang="scss">
.el-card {
  width: 100%;
  height: 100%;
}
</style>
